/**
 * ITabcontrol使用说明： param 对象
 * param.navId tabHeader容器id
 * param.contentId tabContent容器id
 * param.defaultTabId 默认选中的tabId
 * param.loadAll 是否一次加载所有的选项内容，默认false，暂未实现true
 * param.selectClass tabHeader子项选中样式
 * param.normalClass tabHeader子默认样式
 * param.onSelectChange 绑定切换select回调事件(函数)
 * param.onSelectLoadBefore 加载内容之前回调事件(函数)
 * param.onSelectLoaded 加载完成回调事件(函数)
 * @dependency jquery
 * @author
 */
/*global define $win document:true*/
define(["jquery", "touch"], function($) {
    function ITabControl(param) {
        this.params = $.extend({
            navId: null,
            contentId: null,
            defaultTabId: null,
            loadAll: false,
            selectClass: null,
            normalClass: null,
            onSelectChanged: null,
            onSelectLoadBefore: null,
            onSelectLoaded: null
        }, param);

        //		this.selectTabId = null;
        this.selectIndex = -1;
        this.tabIds = [];
        this.modules = {};
        this.currentModule = null,
            this.loadParams = null;
        this.params.loadAll = false;
        this.$header;
        this.$content;
        this.$errorDiv;

        this._checkParamData();
        this._initUI();
        this._initData();
        this._initEvents();
    }

    /**
     * 检查初始化参数，貌似没有用，可以去掉
     */
    ITabControl.prototype._checkParamData = function() {
        if (!this.params) {
            console.error("参数未指定");
            return;
        }
    };
    ITabControl.prototype._initData = function() {
        if (this.params.loadAll) {
            for (var i = 0; i < this.tabIds.length; i++) {
                //
            }
        } else {
            if (this.selectIndex != -1) {
                var tabId = this.tabIds[this.selectIndex];
                if (this.params.onSelectLoadBefore && typeof this.params.onSelectLoadBefore == "function") {
                    this.params.onSelectLoadBefore.apply(this, [tabId]);
                }
                this._loadTabContentByTabId(tabId);
            }
        }
    };
    ITabControl.prototype._loadTabContentByTabId = function(tabId) {
        var _this = this;
        var tabPage = this.$header.children("[tabId=" + tabId + "]").attr("tabPage") + ".html";
        var tabModule = this.$header.children("[tabId=" + tabId + "]").attr("tabModule");
        var loadParams = null;
        if (this.loadParams != null && this.loadParams[tabId] != null) {
            loadParams = this.loadParams[tabId];
        } else {
            //
        }
        $("#" + tabId).load(tabPage, function() {
            if ($.isNotBlank(tabModule)) {
                $win.log(tabId + "**" + tabPage + "**" + tabModule);
                require([tabModule], function(TabModule) {
                    if ($.isNotBlank(loadParams)) {
                        _this.currentModule = new TabModule(loadParams);
                    } else {
                        _this.currentModule = new TabModule(null);
                    }
                    if (_this._checkPageEvent()) {
                        var context = _this.currentModule;
                        _this.currentModule.initDom.call(context);
                        var xhrArray = _this.currentModule.initData.call(context);
                        try {
                            if (xhrArray && $.isArray(xhrArray)) {
                                $.when.apply($, xhrArray).then(function() {
                                    // 成功
                                    setTimeout(function() {
                                        if (_this.currentModule.beforeShowContent && typeof _this.currentModule.beforeShowContent == "function") {
                                            _this.currentModule.beforeShowContent.call(context, _this);
                                        } else {
                                            _this.showContent();
                                        }
                                        $win.log("initData执行完毕，调用initEvent");
                                        _this.currentModule.initEvent.call(context);
                                    }, 500);
                                }, function(e) {
                                    // 失败
                                    $win.log("initData执行失败，" + e.stack);
                                    _this.showErrorModule();
                                });
                            } else {
                                setTimeout(function() {
                                    if (_this.currentModule.beforeShowContent && typeof _this.currentModule.beforeShowContent == "function") {
                                        _this.currentModule.beforeShowContent.call(context, _this);
                                    } else {
                                        _this.showContent();
                                    }
                                    $win.log("initData未返回xhrArray对象，直接调用initEvent");
                                    _this.currentModule.initEvent.call(context);
                                }, 500);
                            }
                        } catch (e) {
                            $win.log("initData后续错误：" + e.stack);
                            _this.showErrorModule();
                        }
                    } else {
                        $win.log("页面未注册initDom,initData,initEvent函数");
                    }
                    if (_this.params.onSelectLoaded && typeof _this.params.onSelectLoaded == "function") {
                        _this.params.onSelectLoaded.apply(_this, [tabId]);
                    }
                    _this.loadParams = null;
                });
            } else {
                if (_this.params.onSelectLoaded && typeof _this.params.onSelectLoaded == "function") {
                    _this.params.onSelectLoaded.apply(_this, [tabId]);
                }
                _this.loadParams = null;
            }
        });
    };

    ITabControl.prototype.showContent = function() {
        this.$errorDiv.css("display", "none");
        var tabId = this.tabIds[this.selectIndex];
        $("#" + tabId).css("display", "inline-block");
    };

    ITabControl.prototype.showErrorModule = function() {
        var tabId = this.tabIds[this.selectIndex];
        $("#" + tabId).css("display", "none");
        this.$errorDiv.css("display", "inline-block");
    };
    ITabControl.prototype._initUI = function() {
        var _this = this;
        this.$header = $("#" + this.params.navId);
        this.$content = $("#" + this.params.contentId);
        this.$errorDiv = $("<div class=\"tabErrorDiv\">页面内容加载失败，点击重新加载</div>");
        this.$errorDiv.css({
            "width": "100%",
            "height": "100%",
            "border":"1px solid red",
            "text-align": "center",
            "vertical-align": "middle",
            "font-size": "16px",
            "float": "left",
            "display": "none"
        });
        this.$errorDiv.css("line-height", this.$content.height() + "px");
        this.$content.append(this.$errorDiv);
        this.$header.children().each(function(i, e) {
            var tabId = $(e).attr("tabId");
            _this.tabIds.push(tabId);
            var tabContent;
            if (_this.params.defaultTabId == tabId) {
                _this.selectIndex = i;
                $(e).addClass(_this.params.selectClass);
                tabContent = _this._initTabContent(tabId, true);
            } else {
                $(e).addClass(_this.params.normalClass);
                tabContent = _this._initTabContent(tabId, false);
            }
            _this.$content.append($(tabContent));
        });

    };

    ITabControl.prototype._initTabContent = function(tabId, isShow) {
        var tabContent = document.createElement("div");
        tabContent.setAttribute("id", tabId);
        $(tabContent).css({
            "width": "100%",
            "height": "100%",
            "float": "left"
        });
        if (isShow) {
            $(tabContent).css({
                "display": "inline-block"
            });
        } else {
            $(tabContent).css({
                "display": "none"
            });
        }
        return tabContent;
    };

    ITabControl.prototype._initEvents = function() {
        var _this = this;
        this.$header.children().each(function(i, e) {
            var item = $(e);
            item.unbind("click").click(function() {
                var index = _this.$header.children().index(this);
                if (index != _this.selectIndex) {
                    var lastSelectIndex = _this.selectIndex;
                    var lastSelectTabId = null;
                    if (lastSelectIndex != -1) {
                        lastSelectTabId = _this.tabIds[lastSelectIndex];
                        _this.$header.children("[tabId=" + lastSelectTabId + "]").removeClass(_this.params.selectClass).addClass(_this.params.normalClass);
                        $("#" + lastSelectTabId).css({
                            "display": "none"
                        });
                    }
                    _this.selectIndex = index;
                    var currentSelectTabId = _this.tabIds[index];
                    _this.$header.children("[tabId=" + currentSelectTabId + "]").removeClass(_this.params.normalClass).addClass(_this.params.selectClass);
                    if (_this.$header.children("[tabId=" + currentSelectTabId + "]").attr("cacheMode") == "cached") {
                        if ($.isNotBlank($("#" + currentSelectTabId).html())) {
                            $("#" + currentSelectTabId).css({
                                "display": "inline-block"
                            });
                            return;
                        }
                    }
                    $("#" + currentSelectTabId).css({
                        "display": "inline-block"
                    });
                    if (_this.params.onSelectChange && typeof _this.params.onSelectChange == "function") {
                        _this.params.onSelectChange.apply(_this, [lastSelectTabId, currentSelectTabId]);
                    }
                    if (_this.params.onSelectLoadBefore && typeof _this.params.onSelectLoadBefore == "function") {
                        _this.params.onSelectLoadBefore.apply(_this, [currentSelectTabId]);
                    }
                    _this._loadTabContentByTabId(currentSelectTabId);
                }
            });
        });
        this.$errorDiv.unbind("click").click(function() {
            var currentSelectTabId = _this.tabIds[_this.selectIndex];
            if (_this.params.onSelectLoadBefore && typeof _this.params.onSelectLoadBefore == "function") {
                _this.params.onSelectLoadBefore.apply(_this, [currentSelectTabId]);
            }
            _this._loadTabContentByTabId(currentSelectTabId);
        });
        //		var target = document.getElementById(this.params.contentId);
        //		touch.on(target, "touchstart", function(ev) {
        ////			ev.preventDefault();
        //		});
        //
        //		touch.on(target, "swipeleft swiperight", function(ev) {
        //			var index;
        //            if(ev.types == "swipeleft"){
        //				if (_this.selectIndex == _this.tabIds.length - 1) {
        //					index = 0;
        //				} else {
        //					index = _this.selectIndex + 1;
        //				}
        //            }else{
        //				if (_this.selectIndex == 0) {
        //					index = _this.tabIds.length - 1;
        //				} else {
        //					index = _this.selectIndex - 1;
        //				}
        //            }
        //            var selectIndex = _this.tabIds[index];
        //			var expr = "[tabId='" + selectIndex + "']";
        //			_this.$header.children(expr).click();
        //            ev.preventDefault();
        //		});

    };

    ITabControl.prototype.changeTabTo = function(tabId) {
        if (tabId == null) {
            return;
        }
        var expr = "[tabId='" + tabId + "']";
        this.$header.children(expr).click();
    };

    /**
     * 内部函数，用于检测页面对象是否实现了必须的方法
     */
    ITabControl.prototype._checkPageEvent = function() {
        return $.isFunc(this.currentModule.initDom) &&
            $.isFunc(this.currentModule.initData) &&
            $.isFunc(this.currentModule.initEvent);
    };
    return ITabControl;
});
